package com.db.stockexchange.app;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import com.db.stockexchange.network.Client;
import com.db.stockexchange.network.DisconnectListener;
import com.db.stockexchange.network.ResponseListener;
import com.db.stockexchange.proto.Protocol.ExchangeMessage;
import com.google.protobuf.InvalidProtocolBufferException;

import java.awt.Color;

@SuppressWarnings("serial")
public class ExchangeClient extends JFrame {

	private JPanel contentPane;
	private JTextField textField;
	private JButton btnNewButton;
	private JMenu mnConnection;
	private JTextArea textArea;
	
	private Client client;
	private static int nextId = 1;
	
	private Logger logger = Logger.getLogger(ExchangeClient.class.getName());

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					ExchangeClient frame = new ExchangeClient();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public ExchangeClient() {
		setForeground(Color.LIGHT_GRAY);
		setTitle("Simple Exchange Client");
		
		setResizable(false);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		mnConnection = new JMenu("Connection");
		menuBar.add(mnConnection);
		
		JMenuItem mntmConnect = new JMenuItem("Connect");
		mntmConnect.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				String host = JOptionPane.showInputDialog("Enter host", "localhost");
				
				try {
					logger.info("connecting to the server");
					if (client != null) client.stop();
					client = new Client(host);
				} catch (IOException ex) {
					JOptionPane.showMessageDialog(ExchangeClient.this,
							"Failed to connect.",
							"Error",
							JOptionPane.ERROR_MESSAGE);
					logger.warning("connect attemption failed");
					return;
				}
				
				client.addResponseListener(new ResponseListener() {
					
					@Override
					public void responseReceived(byte[] rawMessage) {
						
						String message;
						try {
							ExchangeMessage exchangeMessage = ExchangeMessage.parseFrom(rawMessage);
							
							if (exchangeMessage.hasMessageType() &&
								exchangeMessage.getMessageType() == ExchangeMessage.MessageType.LOGON) {
								textField.setEnabled(true);
								btnNewButton.setEnabled(true);
								mnConnection.setEnabled(false);
								textField.requestFocus();
								JOptionPane.showMessageDialog(ExchangeClient.this, "Connection successful.");
								ExchangeClient.this.setTitle(exchangeMessage.getUsername());
							}
							
							message = exchangeMessage.toString();
						} catch (InvalidProtocolBufferException e) {
							message = "received data in unknown format";
						}
						
						String response = String.format("[%s] %s%n",
								new java.util.Date(),
								message);
						
						logger.info("response from server: " + response);
						try {
							textArea.getDocument().insertString(0, response, null);
						} catch (BadLocationException ignore) {}

					}
				});
				
				client.addDisconnectListener(new DisconnectListener() {
					
					@Override
					public void onDisconnect() {
						textField.setEnabled(false);
						btnNewButton.setEnabled(false);
						mnConnection.setEnabled(true);
						JOptionPane.showMessageDialog(ExchangeClient.this, "Server gone down.");
						logger.severe("server gone down");
						client.stop();
					}
				});
				
				String username = JOptionPane.showInputDialog("Enter username");
				
				(new Thread(client)).start();
				
				try {
					client.write(ExchangeMessage.newBuilder()
							.setMessageType(ExchangeMessage.MessageType.LOGON)
							.setUsername(username)
							.build()
							.toByteArray()
							);
				} catch (IOException ex) {
					JOptionPane.showMessageDialog(ExchangeClient.this,
							"Failed to login.",
							"Error",
							JOptionPane.ERROR_MESSAGE);
					return;
				}
			}
		});
		mnConnection.add(mntmConnect);
		
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);
		
		textField = new JTextField();
		textField.setEnabled(false);
		textField.setBounds(10, 11, 315, 20);
		contentPane.add(textField);
		textField.setColumns(10);
		
		btnNewButton = new JButton("Send");
		btnNewButton.setEnabled(false);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

				Pattern pattern = Pattern.compile("^(b|s) ([0-9]+) ([a-zA-Z]+)( ([0-9\\.]+))?");
				Matcher matcher = pattern.matcher(textField.getText());
				
				byte[] message;
				if (!matcher.matches()) {
					message = "some stuff".getBytes();
				} else {
					ExchangeMessage.Builder msg = ExchangeMessage.newBuilder()
						.setMessageType(ExchangeMessage.MessageType.NEW_ORDER)
						.setSide("b".equals(matcher.group(1)) ? ExchangeMessage.Side.BUY : ExchangeMessage.Side.SELL)
						.setQuantity(Integer.valueOf(matcher.group(2)))
						.setSymbol(matcher.group(3))
						.setClientOrderId(nextId++);
					
					if (matcher.group(5) != null) {
						msg.setPrice(matcher.group(5)).setOrderType(ExchangeMessage.OrderType.LIMIT);
					} else {
						msg.setOrderType(ExchangeMessage.OrderType.MARKET);
					}
						
					message = msg.build().toByteArray();
				}
				
				try {
					logger.info("sending to server: ");
					client.write(message);
				} catch (IOException e) {
					logger.severe("failed to send message: " + e.getMessage());
				}
			}
		});
		
		btnNewButton.setBounds(335, 10, 89, 23);
		contentPane.add(btnNewButton);
		
		textArea = new JTextArea();
		textArea.setEditable(false);
		textArea.setForeground(Color.BLACK);
		textArea.setBackground(Color.LIGHT_GRAY);
//		textArea.setBounds(10, 42, 414, 198);
		
		JScrollPane sp = new JScrollPane(textArea);
		sp.setBounds(10, 42, 414, 198);
		
		contentPane.add(sp);
	}
}
